import React, { useState } from 'react';
import {
  Button,
  Checkbox,
  Divider,
  Dropdown,
  Menu,
  message,
  Popconfirm,
  Space,
  Tooltip,
} from 'antd';
import moment from 'moment';
import { features, useTablePipeline } from 'ali-react-table';
import { AntdBaseTable } from '@/base/TBaseTable';
import { ToFixed } from '../../../tool';
import type { IDataListType, IFormValue } from '../../../type';
import { IMaintenancePlanModalType } from '../../../type';
import styles from './index.less';
import { TODO_OPTIONS_LIST, TYPE_LIST } from '../../../dictionary';
import { HttpCode } from '#/utils/contacts.js';
import { postUpdatePlanState } from '../../../services';
import { ConfirmModal } from '@/pages/ETrade/DealCalenderRedesign/components';

interface IProps {
  /**
   * 数据源
   */
  dataSource?: IDataListType[];
  /**
   * 编辑事件
   */
  onEdit?: (record: IDataListType, type: IMaintenancePlanModalType) => void;
  /**
   * 是否展示检修操作按钮
   */
  overhaul?: boolean;
  /**
   * 按钮权限汇总
   */
  buttonPermissions?: any[];
  /**
   * 表单值
   */
  formValue: IFormValue;
  /**
   * 搜索数据
   */
  onSearch?: (values: IFormValue) => void;
}

const PlanList = (props: IProps) => {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const { dataSource = [], onEdit, overhaul, buttonPermissions = [], formValue, onSearch } = props;
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);

  const _onEdit = (record: IDataListType) => {
    if (record.planState === 2) return;
    onEdit && onEdit(record, IMaintenancePlanModalType.EDIT);
  };

  const _onHandleChangeState = async (r: IDataListType, state: number) => {
    if (r.planState) return;
    const res = await postUpdatePlanState({
      idList: [r.id],
      planState: state,
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      onSearch && onSearch(formValue);
    } else {
      message.error(res?.message || '错误请求');
      onSearch && onSearch(formValue);
    }
  };
  // 更改检修计划状态
  const onDeleteNoticeAndSequence = async (params: { data: any; type: string }) => {
    const { data, type } = params;
    let res: any;
    let hintText: string = '';
    const { nostartArr = [], norepairArr = [], completedArr = [] } = data || {};
    const title = type === '1' ? '已完成' : '取消任务';
    if (completedArr?.length > 0 || norepairArr?.length > 0) {
      hintText = `所选检修计划${
        nostartArr?.length + completedArr?.length + norepairArr?.length
      }项，其中${nostartArr?.length}项检修计划可进行${title}操作，是否确认${title}？`;
    } else {
      hintText = `是否确认${title}？`;
    }
    await ConfirmModal.show({
      title: `批量操作${title}`,
      hintText,
      onOk: async () => {
        res = await postUpdatePlanState({
          idList: [...nostartArr, ...norepairArr],
          planState: type === '1' ? TYPE_LIST.COMPLETED : TYPE_LIST.NO_REPAIR,
        });
        onSearch && onSearch(formValue);
      },
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      message.info(res?.message || '操作成功！');
      setSelectedRowKeys([]);
    } else if (res) {
      message.info(res?.message || '操作失败！');
    }
  };
  // 批量操作
  const onBatch = (e: any) => {
    const warnText = '请选择“检修计划”后操作';
    // if (e.key === '1') {
    //   const hasSave =
    //     buttonPermissions?.filter((item: any) => item.menuCode === 'pendingBatchSaveButtonV2')
    //       ?.length > 0;
    //   if (!hasSave) {
    //     return message.info('请联系管理员获取相关权限');
    //   }
    // } else if (e.key === '2') {
    //   const hasSave =
    //     buttonPermissions?.filter((item: any) => item.menuCode === 'batchReminderButtonV2')
    //       ?.length > 0;
    //   if (!hasSave) {
    //     return message.info('请联系管理员获取相关权限');
    //   }
    // }
    if (selectedRowKeys && selectedRowKeys.length > 0) {
      const nostartArr: any = []; //未开始
      const norepairArr: any = []; //已取消
      const completedArr: any = []; //已完成
      selectedRowKeys.forEach((item) => {
        const obj: any = dataSource.find((i) => i.id === item);
        if (obj?.planState === TYPE_LIST.NO_START) {
          nostartArr.push(obj?.id);
        } else if (obj?.planState === TYPE_LIST.NO_REPAIR) {
          norepairArr.push(obj?.id);
        } else {
          completedArr.push(obj?.id);
        }
      });
      onDeleteNoticeAndSequence({
        data: {
          nostartArr,
          norepairArr,
          completedArr,
        },
        type: e.key, // 1--> 已完成，2--> 已取消
      });
    } else {
      message.info(warnText || '请选择');
    }
  };
  // 批量操作列表
  const batchOperations = (
    <Menu onClick={onBatch}>
      {TODO_OPTIONS_LIST.map((item) => {
        return <Menu.Item key={item.value}>{item.label}</Menu.Item>;
      })}
    </Menu>
  );

  const getColumns = () => {
    const columns = [
      {
        code: 'stationName',
        name: '交易单元',
        lock: true,
        width: 100,
        align: 'center',
        render(v: string) {
          return (
            <div className={styles.reason}>
              <Tooltip placement="topLeft" title={v}>
                {v || '-'}
              </Tooltip>
            </div>
          );
        },
      },
      {
        code: 'startDate',
        name: '起始时间',
        width: 120,
        align: 'center',
        render(v: number, record: IDataListType) {
          return (
            <div className={styles.date}>
              {v && record?.startTime
                ? moment(`${v} ${record?.startTime}`).format('HHmm') === '0000'
                  ? moment(`${v} ${record?.startTime}`).subtract(1, 'day').format('YYYYMMDD 2400')
                  : moment(`${v} ${record?.startTime}`).format('YYYYMMDD HHmm')
                : '-'}
            </div>
          );
        },
      },
      {
        code: 'endDate',
        name: '终止时间',
        width: 120,
        align: 'center',
        render(v: number, record: IDataListType) {
          return (
            <div className={styles.date}>
              {v && record?.endTime
                ? moment(`${v} ${record?.endTime}`).format('HHmm') === '0000'
                  ? moment(`${v} ${record?.endTime}`).subtract(1, 'day').format('YYYYMMDD 2400')
                  : moment(`${v} ${record?.endTime}`).format('YYYYMMDD HHmm')
                : '-'}
            </div>
          );
        },
      },
      {
        code: 'effectCapacity',
        name: '影响容量',
        width: 100,
        align: 'center',
        render(v: number) {
          return <div className={styles.date}>{ToFixed(v, 3) ?? '-'}</div>;
        },
      },
      {
        code: 'tendingDateTime',
        name: '维护时间',
        width: 130,
        align: 'center',
        render(v: number) {
          return <div className={styles.date}>{v ? moment(v).format('YYYYMMDD HHmmss') : '-'}</div>;
        },
      },
      {
        code: 'tendingEvent',
        name: '检修事件',
        width: 260,
        align: 'center',
        render(v: string) {
          return (
            <div className={styles.reason}>
              <Tooltip
                placement="topLeft"
                title={v}
                overlayInnerStyle={{
                  maxHeight: '200px',
                  overflowY: 'auto',
                  minWidth: '300px',
                }}
              >
                {v || '-'}
              </Tooltip>
            </div>
          );
        },
      },
      {
        code: 'planState',
        name: '计划状态',
        width: 80,
        align: 'center',
        render(v: number) {
          switch (v) {
            case 0:
              return <span>未开始</span>;
            case 1:
              return <span className={styles.falSp}>已取消</span>;
            case 2:
              return <span className={styles.rigSp}>已完成</span>;
          }
        },
      },
      {
        code: 'tendingUserName',
        name: '维护人',
        width: 80,
        align: 'center',
        render(v: number) {
          return v || '-';
        },
      },
    ];
    if (onEdit) {
      columns.push({
        code: 'operation',
        name: '操作',
        width: overhaul ? 180 : 60,
        align: 'center',
        // @ts-ignore
        render(v: number, record: any) {
          return (
            <Space split={<Divider type="vertical" />}>
              <div
                className={
                  [0].includes(record.planState) ? styles.options : styles.disabled_options
                }
                onClick={() => _onEdit(record)}
              >
                编辑
              </div>
              {overhaul ? (
                <>
                  {[0].includes(record.planState) ? (
                    <Popconfirm
                      title="是否确认已完成？"
                      onConfirm={() => _onHandleChangeState(record, 2)}
                      okText="确认"
                      cancelText="取消"
                    >
                      <div className={styles.options}>已完成</div>
                    </Popconfirm>
                  ) : (
                    <div className={styles.disabled_options}>已完成</div>
                  )}
                  {[0].includes(record.planState) ? (
                    <Popconfirm
                      title="是否确认已取消？"
                      onConfirm={() => _onHandleChangeState(record, 1)}
                      okText="确认"
                      cancelText="取消"
                    >
                      <div className={styles.options}>取消任务</div>
                    </Popconfirm>
                  ) : (
                    <div className={styles.disabled_options}>取消任务</div>
                  )}
                </>
              ) : null}
            </Space>
          );
        },
      });
    }
    return columns;
  };

  const pipeline = useTablePipeline({ components: { Checkbox } })
    .input({ dataSource, columns: getColumns() as any })
    .primaryKey('id')
    .use(
      features.multiSelect({
        value: selectedRowKeys,
        highlightRowWhenSelected: true,
        checkboxPlacement: 'start',
        checkboxColumn: { lock: true },
        clickArea: 'cell',
        onChange: (a: any) => {
          setSelectedRowKeys(a);
        },
      }),
    )
    .appendRowPropsGetter((): any => {
      const color = '#222629';
      return {
        style: { '--bgcolor': color, '--hover-bgcolor': color },
      };
    });

  return (
    <div className={styles.planlist}>
      <div className={styles.option}>
        <Dropdown
          overlay={batchOperations}
          placement="bottomCenter"
          overlayClassName={styles.dropdownA}
        >
          <Button>批量操作</Button>
        </Dropdown>
      </div>
      <div className={`${styles.content}`}>
        <AntdBaseTable
          useVirtual={{ horizontal: true, vertical: true, header: false }}
          key="id"
          style={{
            '--row-height': '28px',
            '--header-bgcolor': '#383C3E',
            '--header-row-height': '28px',
            '--cell-padding': '4px 16px',
            '--cell-border-vertical': '1px solid #4E5154',
            '--header-cell-border-vertical': '1px solid #4E5154',
            '--bgcolor': '#2222629',
            '--hover-bgcolor': '#2222629',
            '--highlight-bgcolor': '#2222629',
          }}
          {...pipeline.getProps()}
        />
      </div>
    </div>
  );
};

export default PlanList;
